package logic

import (
	"context"
	"encoding/json"
	"fmt"
	"luck/es"
	"luck/model/mysql"
	"strings"

	"luck/luckrpc/internal/svc"
	"luck/luckrpc/luckrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProductAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProductAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProductAddLogic {
	return &ProductAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProductAddLogic) ProductAdd(in *luckrpc.ProductAddRequest) (*luckrpc.ProductAddResponse, error) {
	// todo: add your logic here and delete this line
	if in.Name == "" || in.Taste == "" || in.Ingredient == "" || in.Status == 0 || in.Price == 0 || in.Stock == 0 || in.CategoryId == 0 || in.ImageUrl == "" {
		return nil, fmt.Errorf("字段不得为空")
	}

	var product mysql.Product
	mysql.DB.Debug().Where("name = ?", in.Name).Find(&product)
	if product.ID != 0 {
		return nil, fmt.Errorf("当前商品已存在")
	}

	product = mysql.Product{
		Name:       in.Name,
		Price:      float64(in.Price),
		Stock:      in.Stock,
		Ingredient: in.Ingredient,
		Taste:      in.Taste,
		Status:     in.Status,
		ImageUrl:   in.ImageUrl,
		CategoryId: in.CategoryId,
	}
	err := mysql.DB.Debug().Create(&product).Error
	if err != nil {
		return nil, fmt.Errorf("商品添加失败")
	}

	//同步es
	indexName := "luck_product"
	resp, err := es.ElasticSearchClient.Indices.Exists([]string{indexName})
	if err != nil {
		return nil, fmt.Errorf("索引判断失败")
	}

	//判断索引是否存在，不存在则创建
	if resp.StatusCode != 200 {
		create, err := es.ElasticSearchClient.Indices.Create(indexName)
		if err != nil {
			return nil, err
		}
		if create.IsError() {
			return nil, fmt.Errorf("索引创建失败")
		}
	}

	//插入文档
	productMap := map[string]interface{}{
		"id":         product.ID,
		"name":       product.Name,
		"price":      product.Price,
		"stock":      product.Stock,
		"ingredient": product.Ingredient,
		"taste":      product.Taste,
		"status":     product.Status,
		"imageUrl":   product.ImageUrl,
		"category":   product.CategoryId,
		"created_at": product.CreatedAt,
	}
	doc, err := json.Marshal(productMap)
	if err != nil {
		return nil, fmt.Errorf("格式转化错误")
	}

	indexResp, err := es.ElasticSearchClient.Index(indexName, strings.NewReader(string(doc)), es.ElasticSearchClient.Index.WithRefresh("true"))
	if err != nil {
		return nil, err
	}
	if indexResp.IsError() {
		return nil, fmt.Errorf("文档插入失败")
	}

	return &luckrpc.ProductAddResponse{
		Id: int64(product.ID),
	}, nil
}
